<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{{ ptgb.a2 }}_奇安药品数据中心详情</title>
    <!-- 引入Cropper.js CSS -->
    <link rel="stylesheet" href="/style.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.css" rel="stylesheet">
    <style>
        /* 样式根据需要自行调整 */
        .image-upload-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            list-style: none;
            padding: 0;
        }
        .image-upload-wrapper {
            position: relative;
            width: 100px;
            height: 100px;
            border: 2px dashed #ccc;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            flex-shrink: 0;
        }
        .image-upload-wrapper img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 5px;
        }
        .add-button {
            font-size: 24px;
            color: #aaa;
        }
        /* 裁剪模态框样式 */
        #cropModal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }
        #cropModal .modal-content {
            background: #fff;
            padding: 20px;
            border-radius: 5px;
            position: relative;
            max-width: 90%;
            max-height: 90%;
            overflow: auto;
        }
        #cropModal img {
            max-width: 100%;
            max-height: 80vh;
        }
        #cropModal button {
            margin: 10px 5px 0 0;
        }
        /* 删除按钮样式 */
        .delete-button {
            position: absolute;
            top: 2px;
            right: 2px;
            background: rgba(0,0,0,0.5);
            color: #fff;
            border-radius: 50%;
            cursor: pointer;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
        }
        /* 拖拽时的样式 */
        .sortable-helper {
            border: 2px dashed #000;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="top">
		<div class="qa_flex qa_cont">
			<div class="qa_lay logo">
				<h1>奇安药品数据中心</h1>
			</div>
			<div class="qa_lay">
					<div class="form">
					<div class="label"><button type="submit" class="form_btn" onclick="javascript:history.back();">返回</button></div>
					</div>
			</div>
		</div>
	</div>
    <!-- 表格布局，分两列显示 -->
    <div class="qa_cont qa_table">
		<div class="qa_trmx">
			<div data-bt="医保代码" class="qa_td td1">{{ ptgb.ybm }}</div>
            <div data-bt="商品主键" class="qa_td td2">{{ ptgb.pta25 }}</div>
            <div data-bt="通用名称" class="qa_td td3">{{ ptgb.a2 }}</div>
			<div data-bt="商品名称" class="qa_td td4">{{ ptgb.spmc|default_if_none:''  }}</div>
			<div data-bt="生产企业" class="qa_td td5">{{ ptgb.a8|default_if_none:''  }}</div>
			<div data-bt="批准文号" class="qa_td td6">{{ ptgb.a29|default_if_none:''  }}</div>
			<div data-bt="条形码" class="qa_td td9">{{ ptgb.a40|default_if_none:''  }}</div>
			<div data-bt="规格" class="qa_td td10">{{ ptgb.a9|default_if_none:''  }}</div>
			<div data-bt="转换比" class="qa_td td12">{{ ptgb.a39|default_if_none:''  }}</div>
			<div data-bt="辅单位" class="qa_td td13">{{ ptgb.a3_f|default_if_none:''  }}</div>
			<div data-bt="主单位" class="qa_td td14">{{ ptgb.a3_z|default_if_none:''  }}</div>
			<div data-bt="剂型" class="qa_td td16">{{ ptgb.a53|default_if_none:''  }}</div>
			<div data-bt="医保属性" class="qa_td td22">{{ ptgb.ybsx|default_if_none:''  }}</div>
			<div data-bt="医保限制" class="qa_td td23">{{ ptgb.ybxz|default_if_none:''  }}</div>
			<div data-bt="医保药品名称" class="qa_td td24">{{ ptgb.a2_yb|default_if_none:''  }}</div>
            <div data-bt="医保剂型" class="qa_td td25">{{ ptgb.a53_yb|default_if_none:''  }}</div>
			<div data-bt="医保限价" class="qa_td td27">{{ ptgb.ybxj|default_if_none:''  }}</div>
			<div data-bt="比例1" class="qa_td td28">{{ ptgb.bl1|default_if_none:''  }}</div>
			<div data-bt="比例2" class="qa_td td29">{{ ptgb.bl2|default_if_none:''  }}</div>
			<div data-bt="比例3" class="qa_td td30">{{ ptgb.bl3|default_if_none:''  }}</div>
			<div data-bt="流程状态" class="qa_td td31">{{ ptgb.a61|default_if_none:''  }}</div>
            <div data-bt="追溯码" class="qa_td td32">{{ ptgb.spbsm|default_if_none:''  }}</div>
            <div data-bt="添加日期" class="qa_td td34">{{ ptgb.tja17|default_if_none:''  }}</div>
			<div data-bt="更新日期" class="qa_td td35">{{ ptgb.gxa17|default_if_none:''  }}</div>
		</div>


    <div style="clear:both;display: block;"> </div>

    <!-- 图片上传控件新增部分 -->
    <form id="ptgbForm" method="post" enctype="multipart/form-data" action="">
        {% csrf_token %}
        <ul class="image-upload-container" id="imageUploadContainer">
            <!-- 已上传的图片预览 -->
            {% for pic in existing_pics %}
            <li class="image-upload-wrapper image-preview" data-path="{{ pic }}">
                <img src="/{{ pic }}" alt="Uploaded Image">
                <span class="delete-button" title="删除">×</span>
            </li>
            {% endfor %}
            <!-- 新增的上传按钮 -->
            {% if existing_pics|length < 9 %}
            <li class="image-upload-wrapper" id="addImageWrapper">
                <span class="add-button">+</span>
                <input type="file" accept="image/*" capture="environment" id="imageInput" style="display: none;" multiple>
            </li>
            {% endif %}
        </ul>
        <button type="submit" class="form_btn">提交</button>
    </form>

    <!-- 图片裁剪模态框 -->
    <div id="cropModal">
        <div class="modal-content">
            <img id="cropImage" src="" alt="裁剪图片">
            <div>
                <button id="cropConfirm" class="form_btn">确认裁剪</button>
                <button id="cropCancel" class="form_btn">取消</button>
            </div>
        </div>
    </div>

        <div class="pagination">
            <button type="submit" class="form_btn" onclick="javascript:history.back();">返回</button>
        </div>
	</div>

  </div>

    <!-- 引入必要的JS库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js"></script>
    <!-- 引入Sortable.js用于拖拽排序 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>

    <script>
        const maxImages = 9;
        const maxSize = 3 * 1024 * 1024; // 3MB
        const uploadContainer = document.getElementById('imageUploadContainer');
        const addImageWrapper = document.getElementById('addImageWrapper');
        const imageInput = document.getElementById('imageInput');
        const cropModal = document.getElementById('cropModal');
        const cropImage = document.getElementById('cropImage');
        const cropConfirm = document.getElementById('cropConfirm');
        const cropCancel = document.getElementById('cropCancel');
        let currentFile = null;
        let cropper = null;
        let pendingUploads = []; // 存储待上传的图片Blob对象

        // 初始化Sortable.js
        let sortable = new Sortable(uploadContainer, {
            animation: 150,
            onEnd: function (evt) {
                saveOrder();
            }
        });

        // 点击添加按钮触发文件选择
        if (addImageWrapper) {
            addImageWrapper.addEventListener('click', () => {
                imageInput.click();
            });
        }

        // 文件选择后处理
        imageInput.addEventListener('change', (event) => {
            const files = event.target.files;
            if (files.length === 0) return;

            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                if (file && file.type.startsWith('image/')) {
                    currentFile = file;
                    // 显示裁剪模态框
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        cropImage.src = e.target.result;
                        cropModal.style.display = 'flex';
                        // 初始化Cropper
                        cropper = new Cropper(cropImage, {
                            aspectRatio: 1,
                            viewMode: 1,
                        });
                    };
                    reader.readAsDataURL(file);
                }
            }
        });

        // 确认裁剪
        cropConfirm.addEventListener('click', () => {
            if (cropper) {
                cropper.getCroppedCanvas({ width: 500, height: 500 }).toBlob((blob) => { // 调整裁剪后的图片尺寸
                    if (blob.size > maxSize) {
                        alert('图片大小超过3MB，请重新选择。');
                        cropper.destroy();
                        cropper = null;
                        cropModal.style.display = 'none';
                        return;
                    }
                    pendingUploads.push(blob); // 存储裁剪后的Blob
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        addImagePreview(e.target.result, blob);
                    };
                    reader.readAsDataURL(blob);
                    cropper.destroy();
                    cropper = null;
                    cropModal.style.display = 'none';

                    // 清理文件输入
                    imageInput.value = '';

                    // 如果还可以上传更多图片，确保显示添加按钮
                    if (uploadContainer.querySelectorAll('.image-preview').length < maxImages) {
                        if (!document.getElementById('addImageWrapper')) {
                            addImageWrapper = document.createElement('li');
                            addImageWrapper.classList.add('image-upload-wrapper');
                            addImageWrapper.id = 'addImageWrapper';
                            addImageWrapper.innerHTML = '<span class="add-button">+</span>';
                            uploadContainer.appendChild(addImageWrapper);
                            addImageWrapper.addEventListener('click', () => {
                                imageInput.click();
                            });
                        }
                    } else {
                        if (addImageWrapper) {
                            addImageWrapper.remove();
                        }
                    }
                }, 'image/jpeg', 0.8);
            }
        });

        // 取消裁剪
        cropCancel.addEventListener('click', () => {
            if (cropper) {
                cropper.destroy();
                cropper = null;
            }
            cropModal.style.display = 'none';
            imageInput.value = ''; // 重置文件输入
        });

        // 添加图片预览
        function addImagePreview(src, blob) {
            const currentImages = uploadContainer.querySelectorAll('.image-preview').length;
            if (currentImages >= maxImages) {
                alert('最多只能上传9张图片。');
                return;
            }

            const previewWrapper = document.createElement('li');
            previewWrapper.classList.add('image-upload-wrapper', 'image-preview');

            const img = document.createElement('img');
            img.src = src;
            previewWrapper.appendChild(img);

            // 添加删除按钮
            const deleteBtn = document.createElement('span');
            deleteBtn.classList.add('delete-button');
            deleteBtn.innerText = '×';
            previewWrapper.appendChild(deleteBtn);

            // 事件绑定：删除图片
            deleteBtn.addEventListener('click', () => {
                removeImage(previewWrapper);
            });

            // 插入到上传容器前
            uploadContainer.insertBefore(previewWrapper, addImageWrapper);

            // 隐藏添加按钮如果达到最大数量
            if (uploadContainer.querySelectorAll('.image-preview').length >= maxImages) {
                if (addImageWrapper) {
                    addImageWrapper.style.display = 'none';
                }
            }
        }

        // 移除图片预览
        function removeImage(previewWrapper) {
            // 如果是已上传的图片，发送删除请求
            const imagePath = previewWrapper.getAttribute('data-path');
            if (imagePath) {
                fetch("{% url 'delete_image' ptgb.pta25 %}", {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': '{{ csrf_token }}',
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        'image_path': imagePath
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('图片删除成功。');
                        previewWrapper.remove();
                        // 显示添加按钮
                        if (uploadContainer.querySelectorAll('.image-preview').length < maxImages) {
                            if (!addImageWrapper) {
                                const newAddButton = document.createElement('li');
                                newAddButton.classList.add('image-upload-wrapper');
                                newAddButton.id = 'addImageWrapper';
                                newAddButton.innerHTML = '<span class="add-button">+</span>';
                                uploadContainer.appendChild(newAddButton);
                                newAddButton.addEventListener('click', () => {
                                    imageInput.click();
                                });
                            }
                        }
                    } else {
                        alert('图片删除失败：' + data.message);
                    }
                })
                .catch(err => {
                    console.error(err);
                    alert('图片删除出错。');
                });
            } else {
                // 如果是未上传的图片（待上传），仅从页面移除
                previewWrapper.remove();
            }
        }

        // 表单提交时，上传待上传的图片
        const ptgbForm = document.getElementById('ptgbForm');
        ptgbForm.addEventListener('submit', (e) => {
            e.preventDefault(); // 防止默认提交

            if (pendingUploads.length > 0) {
                const formData = new FormData();

                pendingUploads.forEach((blob, index) => {
                    formData.append('images', blob, `image_${index}.jpg`);
                });

                fetch("{% url 'upload_images' ptgb.pta25 %}", {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': '{{ csrf_token }}',
                    },
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('图片上传成功！');
                        // 重新加载页面以显示已上传的图片
                        window.location.reload();
                    } else {
                        alert('图片上传失败：' + data.message);
                    }
                })
                .catch(err => {
                    console.error(err);
                    alert('图片上传出错。');
                });
            } else {
                alert('没有需要上传的图片。');
            }
        });

        // 保存图片顺序
        function saveOrder() {
            const orderedPics = [];
            const previews = uploadContainer.querySelectorAll('.image-preview');
            previews.forEach(preview => {
                const path = preview.getAttribute('data-path');
                if (path) {
                    orderedPics.push(path);
                }
            });

            fetch("{% url 'reorder_images' ptgb.pta25 %}", {
                method: 'POST',
                headers: {
                    'X-CSRFToken': '{{ csrf_token }}',
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    'ordered_pics[]': orderedPics
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    console.log('图片顺序更新成功。');
                } else {
                    alert('图片顺序更新失败：' + data.message);
                }
            })
            .catch(err => {
                console.error(err);
                alert('图片顺序更新出错。');
            });
        }
    </script>
</body>
</html>